#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

/* 互斥锁 */
pthread_mutex_t mutex;

/* 打印 */
void printer(char *str)
{
    /* 上锁 */
    pthread_mutex_lock(&mutex);
    while (*str != '\0') {
        putchar(*str);
        fflush(stdout);
        str++;
        sleep(1);
    }
    printf("\n");
    /* 解锁 */
    pthread_mutex_unlock(&mutex);
}

void *thread_fun_1(void *arg)
{
    char *str = "hello";
    printer(str);
}

void *thread_fun_2(void *arg)
{
    char *str = "world";
    printer(str);
}

int main(void)
{
    pthread_t tid1, tid2;

    /* 初始化互斥锁 */
    pthread_mutex_init(&mutex, NULL);

    /* 创建2个线程 */
    pthread_create(&tid1, NULL, thread_fun_1, NULL);
    pthread_create(&tid2, NULL, thread_fun_2, NULL);

    /* 等待线程结束 */
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    
    /* 销毁互斥锁 */
    pthread_mutex_destroy(&mutex);

    return 0;
}